<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />


        <!-- 统计卡片 -->
        <div class="statistics-cards" style="margin-bottom: 20px;">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-card shadow="hover" class="stat-card">
                        <div class="stat-content">
                            <div class="stat-icon" style="background: #409eff;">
                                <el-icon><Money /></el-icon>
                            </div>
                            <div class="stat-info">
                <div class="stat-number">￥{{ statistics.totalOrderAmount || 0 }}</div>
                <div class="stat-label">当前月份订单总额</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="6">
                    <el-card shadow="hover" class="stat-card">
                        <div class="stat-content">
                            <div class="stat-icon" style="background: #67c23a;">
                                <el-icon><View /></el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">￥{{ statistics.seeOrderBonus || 0 }}</div>
                                <div class="stat-label">见单奖总额</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="6">
                    <el-card shadow="hover" class="stat-card">
                        <div class="stat-content">
                            <div class="stat-icon" style="background: #409eff;">
                                <el-icon><User /></el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">￥{{ statistics.directBonus || 0 }}</div>
                                <div class="stat-label">直推奖总额</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="6">
                    <el-card shadow="hover" class="stat-card">
                        <div class="stat-content">
                            <div class="stat-icon" style="background: #e6a23c;">
                                <el-icon><Star /></el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">￥{{ statistics.levelBonus || 0 }}</div>
                                <div class="stat-label">平级奖总额</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <!-- 第二行统计卡片 -->
        <div class="statistics-cards" style="margin-bottom: 20px;">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-card shadow="hover" class="stat-card">
                        <div class="stat-content">
                            <div class="stat-icon" style="background: #f56c6c;">
                                <el-icon><Trophy /></el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">￥{{ statistics.dividendBonus || 0 }}</div>
                                <div class="stat-label">分红总额</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="6">
                    <el-card shadow="hover" class="stat-card">
                        <div class="stat-content">
                            <div class="stat-icon" style="background: #909399;">
                                <el-icon><Clock /></el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">{{ statistics.todayCount || 0 }}</div>
                                <div class="stat-label">今日记录数</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <!-- 表格顶部菜单 -->
        <TableHeader
            :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('linkage.incomeLog.quick Search Fields') })"
        >
            <el-button type="warning" @click="showAdvanceDividendDialog" style="margin-left: 20px;">
                <el-icon><Money /></el-icon>
                提前分红测试
            </el-button>
        </TableHeader>

        <!-- 表格 -->
        <Table ref="tableRef"></Table>

        <!-- 表单 -->
        <PopupForm />

        <!-- 收益图表弹窗 -->
        <el-dialog v-model="chartVisible" title="收益统计图表" width="80%" :close-on-click-modal="false">
            <div class="chart-container" style="height: 400px;">
                <!-- 这里可以集成图表库，如 ECharts -->
                <div style="text-align: center; padding: 100px; color: #999;">
                    图表功能开发中...
                </div>
            </div>
        </el-dialog>

        <!-- 提前分红对话框 -->
        <el-dialog v-model="advanceDividendVisible" title="提前分红" width="600px" :close-on-click-modal="false">
            <el-form :model="advanceDividendForm" label-width="120px">
                <el-form-item label="用户ID" required>
                    <el-input 
                        v-model="advanceDividendForm.user_id" 
                        placeholder="请输入用户ID"
                        clearable
                    />
                </el-form-item>
                <el-form-item label="测试月份" required>
                    <el-date-picker
                        v-model="advanceDividendForm.month"
                        type="month"
                        placeholder="选择月份"
                        format="YYYY-MM"
                        value-format="YYYY-MM"
                        style="width: 100%"
                    />
                </el-form-item>
                <el-form-item label="分红等级" required>
                    <el-select v-model="advanceDividendForm.level" placeholder="选择分红等级" style="width: 100%">
                        <el-option label="一星分红" :value="1" />
                        <el-option label="二星分红" :value="2" />
                        <el-option label="三星分红" :value="3" />
                    </el-select>
                </el-form-item>
                <el-alert
                    title="注意"
                    type="warning"
                    description="此功能用于测试分红计算逻辑，请谨慎使用。执行后将会为指定用户计算并分配分红收益。"
                    show-icon
                    :closable="false"
                    style="margin-top: 20px;"
                />
            </el-form>
            <template #footer>
                <el-button @click="advanceDividendVisible = false">取消</el-button>
                <el-button type="warning" @click="executeAdvanceDividend" :loading="advanceDividendLoading">
                    单用户测试
                </el-button>
                <el-button type="danger" @click="executeFullDividend" :loading="advanceDividendLoading">
                    全量分红测试
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { onMounted, provide, ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Money, View, Star, Clock, Download, TrendCharts, User, Trophy, Lock } from '@element-plus/icons-vue'
import PopupForm from './popupForm.vue'
import { baTableApi } from '/@/api/common'
import createAxios from '/@/utils/axios'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'

defineOptions({
    name: 'linkage/incomeLog',
})

const { t } = useI18n()
const tableRef = ref()
const chartVisible = ref(false)

// 提前分红相关状态
const advanceDividendVisible = ref(false)
const advanceDividendLoading = ref(false)
const advanceDividendForm = reactive({
    user_id: '',
    month: '',
    level: 1
})
const statistics = reactive({
    totalIncome: 0,
    seeOrderBonus: 0,
    directBonus: 0,
    levelBonus: 0,
    dividendBonus: 0,
    availableAmount: 0,
    frozenAmount: 0,
    todayCount: 0,
    totalOrderAmount: 0
})

// 自定义操作按钮
const optButtons: OptButton[] = [
    ...defaultOptButtons(['edit', 'delete']),
    // {
    //     render: 'tipButton',
    //     name: 'detail',
    //     title: '查看详情',
    //     text: '',
    //     type: 'info',
    //     icon: 'fa fa-eye',
    //     click: (row: any) => {
    //         showIncomeDetail(row)
    //     }
    // }
]

/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/linkage.IncomeLog/'),
    {
        pk: 'id',
        column: [
            { type: 'selection', align: 'center', operator: false },
            { label: t('linkage.incomeLog.id'), prop: 'id', align: 'center', width: 70, operator: 'RANGE', sortable: 'custom' },
            { 
                label: '收益用户', 
                prop: 'user.nickname', 
                align: 'center', 
                width: 200
            },
            { 
                label: '来源用户', 
                prop: 'fromUser.nickname', 
                align: 'center', 
                width: 200
            },
            { 
                label: '收益类型', 
                prop: 'income_type', 
                align: 'center', 
                width: 120,
                render: 'tag',
                replaceValue: { '1': '见单奖', '2': '平级奖', '3': '直推奖', '4': '分红', '5': '返佣' },
                custom: { '1': 'success', '2': 'warning', '3': 'primary', '4': 'danger', '5': 'info' }
            },
            { 
                label: '收益金额', 
                prop: 'amount', 
                align: 'center', 
                width: 150
            },
            { 
                label: '冻结金额', 
                prop: 'frozen_amount', 
                align: 'center', 
                width: 120
            },
            { 
                label: '可用金额', 
                prop: 'available_amount', 
                align: 'center', 
                width: 120
            },
            { 
                label: '状态', 
                prop: 'status', 
                align: 'center', 
                width: 100,
                render: 'tag',
                replaceValue: { '1': '正常', '0': '冻结' },
                custom: { '1': 'success', '0': 'danger' }
            },
            { 
                label: '备注信息', 
                prop: 'unfreeze_condition', 
                align: 'center', 
                width: 200,
                showOverflowTooltip: true
            },
            { 
                label: '创建时间', 
                prop: 'create_time', 
                align: 'center', 
                render: 'datetime', 
                operator: 'RANGE', 
                sortable: 'custom', 
                width: 160, 
                timeFormat: 'yyyy-mm-dd hh:MM:ss' 
            },
            { label: t('Operate'), align: 'center', width: 120, render: 'buttons', buttons: optButtons, operator: false },
        ],
        dblClickNotEditColumn: [undefined],
    },
    {
        defaultItems: { amount: 0, frozen_amount: 0, available_amount: 0, status: '1' },
    }
)

provide('baTable', baTable)

// 获取统计数据
const getStatistics = async () => {
    try {
        // 直接调用 API 获取数据，而不是通过 baTable.onTableHeaderAction
        const response: any = await baTable.api.index(baTable.table.filter)
        if (response && response.data) {
            const data = response.data
            
            // 使用 Object.assign 确保响应式更新
            Object.assign(statistics, {
                totalIncome: data.totalIncome || 0,
                seeOrderBonus: data.seeOrderBonus || 0,
                directBonus: data.directBonus || 0,
                levelBonus: data.levelBonus || 0,
                dividendBonus: data.dividendBonus || 0,
                availableAmount: data.availableAmount || 0,
                frozenAmount: data.frozenAmount || 0,
                todayCount: data.todayCount || 0,
                totalOrderAmount: data.totalOrderAmount || 0
            });
        }
    } catch (error) {
        console.error('获取统计数据失败:', error)
    }
}

// 导出数据
const exportData = () => {
    ElMessage.success('导出功能开发中...')
}

// 显示收益图表
const showIncomeChart = () => {
    chartVisible.value = true
}

// 查看收益详情
const showIncomeDetail = (row: any) => {
    ElMessage.info(`查看收益详情：${row.id}`)
}

// 显示提前分红对话框
const showAdvanceDividendDialog = () => {
    // 重置表单
    advanceDividendForm.user_id = ''
    advanceDividendForm.month = new Date().toISOString().slice(0, 7) // 当前月份
    advanceDividendForm.level = 1
    advanceDividendVisible.value = true
}

// 执行单用户分红测试
const executeAdvanceDividend = async () => {
    if (!advanceDividendForm.user_id) {
        ElMessage.error('用户ID不能为空')
        return
    }
    
    if (!advanceDividendForm.month) {
        ElMessage.error('请选择测试月份')
        return
    }
    
    advanceDividendLoading.value = true
    
    try {
        // 调用后端API执行单用户分红测试
        const res = await createAxios({
            url: `/admin/linkage.IncomeLog/advanceDividend?user_id=${advanceDividendForm.user_id}&month=${advanceDividendForm.month}&level=${advanceDividendForm.level}`,
            method: 'POST'
        }, {
            loading: true
        }, {
            text: '执行单用户分红测试中...'
        })
        
        if (res.code === 1) {
            ElMessage.success('单用户分红测试执行成功！')
            advanceDividendVisible.value = false
            // 先刷新表格数据，然后刷新统计数据（避免重复请求）
            await baTable.getIndex()
            await getStatistics()
        } else {
            // 将业务提醒作为信息提示，而不是错误
            ElMessage.info(res.msg || '没有符合条件的用户')
        }
    } catch (error) {
        console.error('执行单用户分红测试失败:', error)
        ElMessage.error('执行单用户分红测试失败，请检查网络连接')
    } finally {
        advanceDividendLoading.value = false
    }
}

// 执行全量分红测试
const executeFullDividend = async () => {
    if (!advanceDividendForm.month) {
        ElMessage.error('请选择测试月份')
        return
    }
    
    // 确认执行全量分红
    await ElMessageBox.confirm(
        `确定要对 ${advanceDividendForm.month} 月执行全量分红测试吗？这将给所有符合条件的用户发放分红。`,
        '确认全量分红',
        {
            confirmButtonText: '确定执行',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
    
    advanceDividendLoading.value = true
    
    try {
        // 调用后端API执行全量分红（不传user_id参数）
        const res = await createAxios({
            url: `/admin/linkage.IncomeLog/advanceDividend?month=${advanceDividendForm.month}&level=${advanceDividendForm.level}`,
            method: 'POST'
        }, {
            loading: true
        }, {
            text: '执行全量分红测试中...'
        })
        
        if (res.code === 1) {
            ElMessage.success('全量分红测试执行成功！')
            advanceDividendVisible.value = false
            // 先刷新表格数据，然后刷新统计数据（避免重复请求）
            await baTable.getIndex()
            await getStatistics()
        } else {
            // 将业务提醒作为信息提示，而不是错误
            ElMessage.info(res.msg || '没有符合条件的用户')
        }
    } catch (error) {
        if (error !== 'cancel') { // 用户取消确认不显示错误
            console.error('执行全量分红测试失败:', error)
            ElMessage.error('执行全量分红测试失败，请检查网络连接')
        }
    } finally {
        advanceDividendLoading.value = false
    }
}

onMounted(async () => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    
    // 先等待表格数据加载完成
    await baTable.getIndex()
    
    // 然后初始化排序和拖拽
    baTable.initSort()
    baTable.dragSort()
    
    // 最后获取统计数据（避免重复请求）
    await getStatistics()
})
</script>

<style scoped lang="scss">
.statistics-cards {
    .stat-card {
        .stat-content {
            display: flex;
            align-items: center;
            gap: 16px;
            
            .stat-icon {
                width: 48px;
                height: 48px;
                border-radius: 8px;
                display: flex;
                align-items: center;
                justify-content: center;
                color: white;
                font-size: 20px;
            }
            
            .stat-info {
                flex: 1;
                
                .stat-number {
                    font-size: 24px;
                    font-weight: bold;
                    color: #303133;
                    line-height: 1;
                }
                
                .stat-label {
                    font-size: 14px;
                    color: #909399;
                    margin-top: 4px;
                }
            }
        }
    }
}

.chart-container {
    background: #f5f5f5;
    border-radius: 8px;
    padding: 20px;
}
</style>
